<?php
include_once("../../Functions/fileSystem.php");
if (empty($_POST) && $_POST) {
    echo "<script>
    alert('上传的文件超过了php.ini中post_max_size选项限制的值！');window.location.href='./Modify_V.php'
    </script>";
} else {
    include_once("../../Functions/connectDatabase.php");
    get_connection();
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        if (empty($_POST["title"])) {
            echo "<script>
            alert('新闻标题不能为空！');window.location.href='./Modify_V.php'
            </script>";
        } else {
            $id = $_POST["id"];
            $title = $_POST["title"];
            $category = $_POST["category"];
            $content = $_POST["content"];
            $user = "admin";       //测试用，后续根据session写入发布用户
            $time = date("Y-m-d H:i:s");
            $file_name = $_FILES["attachment"]["name"];
            if(!empty($file_name)){
                $message = upload($_FILES["attachment"], "../../Public/Uploads");
                if ($message == "文件上传成功！" || $message == "没有选择上传附件！") {
                    $sql = "UPDATE news SET user_id='$user',category_id='$category',news_title='$title',
                    news_content='$content',news_publish_time='$time',news_attachment='$file_name'
                    WHERE news_id='$id'";
                    if (mysqli_query($conn, $sql)) {
                        echo "<script>alert('修改成功！');window.location.href='./adminShow.php'</script>";
                    } else {
                        $error = mysqli_error($conn);
                        $error = str_replace('\'', '', $error);
                        echo "<script>alert('修改失败！$error');window.location.href='./adminShow.php'</script>";
                    }
                } else {
                    echo "<script>alert('修改失败！$message');window.location.href='./adminShow.php'</script>";
                }
            }else{
                    $sql = "UPDATE news SET user_id='$user',category_id='$category',news_title='$title',
                    news_content='$content',news_publish_time='$time'WHERE news_id='$id'";
                    if (mysqli_query($conn, $sql)) {
                        echo "<script>alert('修改成功！');window.location.href='./adminShow.php'</script>";
                    } else {
                        $error = mysqli_error($conn);
                        $error = str_replace('\'', '', $error);
                        echo "<script>alert('修改失败！$error');window.location.href='./adminShow.php'</script>";
                    }
                }
            
            
            $message = urlencode($message);
            //header("Location:List.php?message=$message");
        }
    }
    close_connection();
}
